package tw.asap.plus.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import java.io.Serializable;
import java.lang.reflect.Type;

import tw.asap.plus.common.ConstValue;


/**
 * Created by chenfeiyue on 15/7/6.
 */
public class SPUtil {
    private static SPUtil saver;
    private final static int MODE = Context.MODE_WORLD_READABLE
            | Context.MODE_WORLD_WRITEABLE | Context.MODE_MULTI_PROCESS;
    private static SharedPreferences sp;

    public static SPUtil getInstance(Context context) {
        if (saver == null) {
            synchronized (SPUtil.class) {
                if (saver == null) {
                    saver = new SPUtil();
                    sp = context.getApplicationContext().getSharedPreferences(ConstValue.Sp.NAME, MODE);
                }
            }
        }
        return saver;
    }

    public void save(String key, String value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public void save(String key, long value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(key, value);
        editor.commit();
    }

    public void save(String key, int value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    public void save(String key, float value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat(key, value);
        editor.commit();
    }

    public void save(String key, boolean value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    public void saveSerializable(String key, Serializable serializable) {
        SharedPreferences.Editor editor = sp.edit();
        String json = new Gson().toJson(serializable);
        editor.putString(key, json);
        editor.commit();
    }

    public Serializable getSerializable(String key, Type type) {
        String json = sp.getString(key, "");
        return new Gson().fromJson(json, type);
    }


    public boolean getBoolean(String key, boolean defValue) {
        return sp.getBoolean(key, defValue);
    }

    public String getString(String key, String defValue) {
        return sp.getString(key, defValue);
    }

    public int getInt(String key, int defValue) {
        return sp.getInt(key, defValue);
    }

    public long getLong(String key, long defValue) {
        return sp.getLong(key, defValue);
    }

    public float getFloat(String key, float defValue) {
        return sp.getFloat(key, defValue);
    }

}
